<template>
  <!-- 口令验证对话框 -->
  <el-dialog
    v-model="showPasswordDialog"
    title="访问验证"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <el-form @submit.prevent="verifyPasswordInput">
      <el-form-item label="请输入访问口令：">
        <el-input
          v-model="inputPassword"
          type="password"
          placeholder="请输入口令"
          show-password
          @keyup.enter="verifyPasswordInput"
          autofocus
        ></el-input>
      </el-form-item>
      <div class="flex justify-end gap-2">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="verifyPasswordInput" :loading="verifying">
          确认
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <!-- 主内容区 -->
  <div v-show="!showPasswordDialog">
    <mt-preview ref="MtPreviewRef" @on-event-call-back="onEventCallBack"></mt-preview>
  </div>
</template>
<script setup lang="ts">
import { MtPreview } from '@/export';
import { onMounted, ref } from 'vue';
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
import { verifyPassword, hasPassword } from '@/utils/crypto';

const MtPreviewRef = ref<InstanceType<typeof MtPreview>>();
const showPasswordDialog = ref(false);
const inputPassword = ref('');
const verifying = ref(false);
let exportJsonData: any = null;

const onEventCallBack = (type: string, item_id: string) => {
  if (type == 'test-dialog') {
    ElMessage.success(`获取到了id:${item_id}`);
  }
};

const verifyPasswordInput = async () => {
  if (!exportJsonData) {
    ElMessage.error('数据加载失败');
    return;
  }

  const passwordData = exportJsonData.canvasCfg?.access_password;

  if (!hasPassword(passwordData)) {
    // 没有设置口令，直接加载
    loadPreviewData();
    return;
  }

  verifying.value = true;

  try {
    const isValid = await verifyPassword(inputPassword.value, passwordData.hash, passwordData.salt);

    if (isValid) {
      setTimeout(() => {
        verifying.value = false;
        showPasswordDialog.value = false;
        loadPreviewData();
        ElMessage.success('验证成功');
      }, 500);
    } else {
      verifying.value = false;
      ElMessage.error('口令错误，请重新输入');
      inputPassword.value = '';
    }
  } catch (error) {
    verifying.value = false;
    ElMessage.error('验证过程中出现错误');
    console.error('Password verification error:', error);
  }
};

const handleCancel = () => {
  // 返回上一页或关闭窗口
  if (window.history.length > 1) {
    window.history.back();
  } else {
    window.close();
  }
};

const loadPreviewData = () => {
  if (exportJsonData && MtPreviewRef.value) {
    MtPreviewRef.value.setImportJson(exportJsonData);
  }
};

onMounted(() => {
  try {
    // 获取sessionStorage中的数据
    const rawData = sessionStorage.getItem('exportJson');

    if (!rawData) {
      ElMessage.error('未找到预览数据');
      console.error('No exportJson found in sessionStorage');
      return;
    }

    // 尝试解析JSON
    try {
      exportJsonData = JSON.parse(rawData);
    } catch (parseError) {
      ElMessage.error('数据格式错误：JSON解析失败');
      console.error('JSON parse error:', parseError);
      console.error('Raw data sample:', rawData.substring(0, 1000) + '...');
      return;
    }

    if (!exportJsonData) {
      ElMessage.error('解析后的数据为空');
      return;
    }

    // 验证数据结构
    if (!exportJsonData.canvasCfg) {
      ElMessage.error('数据格式错误：缺少canvasCfg配置');
      console.error('Invalid data structure - missing canvasCfg:', exportJsonData);
      return;
    }

    const passwordData = exportJsonData.canvasCfg?.access_password;

    if (hasPassword(passwordData)) {
      // 需要口令验证
      showPasswordDialog.value = true;
    } else {
      // 无需验证，直接加载
      loadPreviewData();
    }
  } catch (error) {
    ElMessage.error('预览数据加载失败');
    console.error('Preview data load error:', error);

    // 尝试清理可能损坏的数据
    try {
      sessionStorage.removeItem('exportJson');
    } catch (cleanError) {
      console.error('Failed to clean sessionStorage:', cleanError);
    }
  }
});
</script>

<style scoped>
.el-dialog {
  border-radius: 8px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
